package dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import org.snowin.common.SessionData;

public class BaseDao
{
    protected String hostName;
    private String url = "";
    private String user = "devadmin";
    private String pwd = "devadmin1";
    Logger logger;
    Connection conn;

    public BaseDao(SessionData sessionData)
    {
        this.hostName = sessionData.getHostName();
        this.logger = sessionData.getLogger();
        chooseDB();
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            this.conn = DriverManager.getConnection(this.url, this.user, this.pwd);
        }
        catch (Exception e)
        {
            this.logger.info("Connect to DB Error", e);
        }
    }

    private void chooseDB()
    {
        if (this.hostName.contains("release.com"))
        {
            this.url = "jdbc:mysql://127.0.0.1:3306/release_envdb";
            this.user = "user";
            this.pwd = "passwd";
        }
        else if (this.hostName.contains("onlinehost.com"))
        {
            this.url = "jdbc:mysql://127.0.0.1:3306/online_db";
            this.user = "user";
            this.pwd = "passwd";
        }
        else if (this.hostName.contains("other.host.com"))
        {
            this.url = "jdbc:mysql://127.0.0.1:3306/db_db";
            this.user = "user";
            this.pwd = "passwd";
        }
    }

    public ResultSet executeSql(String sql)
    {
        ResultSet rs = null;
        try
        {
            Statement stmt = this.conn.createStatement();

            rs = stmt.executeQuery(sql);
        }
        catch (SQLException e)
        {

            this.logger.info("execute the sql failed", e);
            return null;
        }

        return rs;
    }

    protected void closeConnection()
    {
        try
        {
            this.conn.commit();
            this.conn.close();
        }
        catch (Exception e)
        {
            this.logger.info("Close DB connection failed", e);
        }
    }
}
